import { Button, Form, Input, Modal, Col, Row } from "antd";
import action from "@/store/action";
import { useDispatch, useSelector } from "react-redux";
import { api } from "@/api";
import { useMyContext } from "@/hooks";
import { useCallback, useEffect, useRef, useState } from "react";

let count = 6;
const RegisterModal = () => {
  const [formIns] = Form.useForm();
  const { registerFlag } = useSelector((state) => state.app);
  const dispath = useDispatch();
  const { messageApi } = useMyContext();
  // const [count, setCount] = useState(5);

  const [str, setStr] = useState("获取验证码");
  const [loadingC, setLoadingC] = useState(false);
  const [loading, setLoading] = useState(false);

  const ValidateEmail = useCallback(async (_, value) => {
    if (!value || value.trim() === "") return Promise.reject("请输入内容");
    const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    if (!reg.test(value)) {
      messageApi.warning("请输入正确的邮箱格式");
      return Promise.reject("请输入正确的邮箱格式");
    }
    //校验优先是否被注册
    let { code, message } = await api.hasEmail({ email: value });
    //code为0代表验证通过
    if (code !== 0) {
      return Promise.reject(message);
    }
    return Promise.resolve();
  }, []);
  let timer = null;
  function setTime() {
    count--;
    if (count === 0) {
      clearInterval(timer);
      timer = null;
      count = 6;
      setStr("获取验证码");
      setLoadingC(false);
    } else {
      setStr(`${count}秒重新获取`);
    }
  }

  async function getCode() {
    //点击获取验证码也需要校验优先是否正确
    try {
      await formIns.validateFields(["email"]); //指定校验字段
      setLoadingC(true);
      setTime();
      if (!timer) timer = setInterval(setTime, 1000);
      let email = formIns.getFieldValue("email");
      //获取六位验证码发送到邮箱
      let { code } = await api.sendCode({ email: email });

      if (code === 0) {
        messageApi.info("发送成功");
      } else {
        messageApi.info("发送失败");
      }
    } catch (error) {
      messageApi.info("发送失败");
      console.log(error);
    }
  }
  async function handleRegister() {
    try {
      await formIns.validateFields();
      setLoading(true);
      // 获取内容
      const value = formIns.getFieldsValue();
      let res = await api.register(value);
      if (res.code === 0) {
        messageApi.success("注册成功");
        dispath(action.app.setRegisterFlag(false));
        dispath(action.app.setLoginFlag(true));
      } else {
        messageApi.success("注册失败");
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      <Modal
        title="注册"
        open={registerFlag}
        onCancel={() => dispath(action.app.setRegisterFlag(false))}
        width={460}
        centered
        footer={() => {
          return (
            <div style={{ textAlign: "start" }}>
              已有账号？
              <button
                className="register-login-btn"
                onClick={() => {
                  dispath(action.app.setRegisterFlag(false));
                  dispath(action.app.setLoginFlag(true));
                }}
              >
                登录
              </button>
            </div>
          );
        }}
      >
        <Form
          form={formIns}
          name="register"
          className="register-form"
          colon={false}
        >
          <Form.Item
            label="邮箱号"
            name="email"
            rules={[{ validator: ValidateEmail, required: true }]}
            validateTrigger="onBlur"
          >
            <Input />
          </Form.Item>

          <Form.Item label="验证码">
            <Row gutter={8}>
              <Col span={15}>
                <Form.Item
                  name="code"
                  noStyle
                  rules={[{ required: true, message: "请输入六位验证码" }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Button onClick={getCode} loading={loadingC}>
                  {str}
                </Button>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              danger
              className="register-form-button"
              onClick={handleRegister}
              loading={loading}
            >
              注册
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default RegisterModal;
